package com.geekjob1120.geekjob1120pay.support;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

@JsonComponent
@Slf4j
public class MoneyDeserializer extends StdDeserializer<Money> {
    protected MoneyDeserializer() {
        super(Money.class);
    }

    @Override
    public Money deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
        if (org.apache.commons.lang3.math.NumberUtils.isParsable(p.getText())){
            return Money.of(CurrencyUnit.of("CNY"), org.apache.commons.lang3.math.NumberUtils.createBigDecimal(p.getText()));
        }
        else if(org.apache.commons.lang3.StringUtils.isNoneEmpty(p.getText())){
            String[] src = org.apache.commons.lang3.StringUtils.split(p.getText(),' ');
            if(src!=null && src.length == 2 && org.apache.commons.lang3.math.NumberUtils.isParsable(src[1])){
                return Money.of(CurrencyUnit.of(src[0]),org.apache.commons.lang3.math.NumberUtils.createBigDecimal(src[1]));
            }
        }
        throw new RuntimeException(p.getText() + "无法解析为Money对象");
    }
}
